import { ExpertList } from '@/api/expert';
import { Empty, Popup } from '@antmjs/vantui';
import {
  Input,
  PickerView,
  PickerViewColumn,
  Text,
  View,
} from '@tarojs/components';
import { useMemo, useState } from 'react';
import { useRequest } from 'taro-hooks';

export default function useExpertSelector(props: { onConfirm: Function }) {
  const [show, setShow] = useState<boolean>(false);
  const [keyword, setKeyword] = useState<string>('');

  const { data } = useRequest(() => ExpertList({ name: keyword }), {
    refreshDeps: [keyword],
  });

  const [index, setIndex] = useState<number>(0);
  const souceData = useMemo(() => data?.[index as number], [index, data]);

  function renderNode() {
    return (
      <Popup show={show} position='bottom' round>
        <View className='flex justify-between'>
          <Text className='p-4 block' onClick={() => setShow(false)}>
            取消
          </Text>
          <Text
            className='p-4 block text-primary'
            onClick={() => {
              souceData && props.onConfirm(souceData);
              setShow(false);
            }}
          >
            确定
          </Text>
        </View>
        <View className='px-4 mb-2'>
          <Input
            alwaysEmbed
            placeholder='请输入关键词'
            className='bg-[#F6F7FB] rounded-lg block px-4 h-10'
            onBlur={(e) => {
              setKeyword(e.detail.value);
            }}
          />
        </View>
        <PickerView
          indicatorStyle='height: 50px;'
          className='h-[500px]'
          onChange={(e) => {
            const index = e.detail.value?.[0];
            setIndex(index);
          }}
        >
          {(Boolean(data?.length) && (
            <PickerViewColumn>
              {data?.map((item) => (
                <View
                  key={item.id}
                  className=' text-center'
                  style={{
                    lineHeight: '50px',
                  }}
                >
                  {item.name}
                </View>
              ))}
            </PickerViewColumn>
          )) || (
            <View className=' w-full flex justify-center'>
              <Empty description='暂无查询结果' />
            </View>
          )}
        </PickerView>
      </Popup>
    );
  }

  return {
    renderNode,
    open: () => setShow(true),
  };
}
